package org.linphone.sub.utils;

/**
 * Created by Xiang on 2018/4/2.
 */

public class ArrayUtil {

	/***
	 * byte[]高低位反转
	 *
	 * @param array
	 */
	public static void reverse(final byte[] array) {
		if (array == null) {
			return;
		}
		//大转小
		short sho;
		for(int x=0;x<array.length-1;x=x+2){
			sho = bytesToIntBig(array,x);
			array[x] = intToBytesBig(sho)[0];
			array[x+1] = intToBytesBig(sho)[1];

		}

	}

	/**
	 * 以大端模式将int转成byte[]
	 */
	public static byte[] intToBytesBig(short value) {
		byte[] src = new byte[2];
		src[0] = (byte) ((value >> 8) & 0xFF);
		src[1] = (byte) (value & 0xFF);
		return src;
	}

	/**
	 * 以小端模式将int转成byte[]
	 *
	 * @param value
	 * @return
	 */
	public static byte[] intToBytesLittle(short value) {
		byte[] src = new byte[2];
		src[1] = (byte) ((value >> 8) & 0xFF);
		src[0] = (byte) (value & 0xFF);
		return src;
	}

	/**
	 * 以大端模式将byte[]转成int
	 */
	public static short bytesToIntBig(byte[] src, int offset) {
		short value;
		value = (short) (((src[offset] & 0xFF) << 8)
				| ((src[offset + 1] & 0xFF)));
		return value;
	}

	/**
	 * 以小端模式将byte[]转成int
	 */
	public static short bytesToIntLittle(byte[] src, int offset) {
		short value;
		value = (short) ((src[offset] & 0xFF)
				| ((src[offset + 1] & 0xFF) << 8));
		return value;
	}

	/**
	 * 以大端模式将byte[]转成int
	 */
	public static int bytesToIntBig2(byte[] src, int offset) {
		int value;
		value = (int) (((src[offset] & 0xFF) << 24)
				| ((src[offset + 1] & 0xFF) << 16)
				| ((src[offset + 2] & 0xFF) << 8)
				| (src[offset + 3] & 0xFF));
		return value;
	}

	/**
	 * 以小端模式将byte[]转成int
	 */
	public static int bytesToIntLittle2(byte[] src, int offset) {
		int value;
		value = (int) ((src[offset] & 0xFF)
				| ((src[offset + 1] & 0xFF) << 8)
				| ((src[offset + 2] & 0xFF) << 16)
				| ((src[offset + 3] & 0xFF) << 24));
		return value;
	}


	/**
	 * 将int数值转换为占四个字节的byte数组，本方法适用于(低位在前，高位在后)的顺序。 和bytesToInt（）配套使用
	 * @param value
	 *            要转换的int值
	 * @return byte数组
	 */
	public static byte[] intToBytesLittle2( int value )
	{
		byte[] src = new byte[4];
		src[3] =  (byte) ((value>>24) & 0xFF);
		src[2] =  (byte) ((value>>16) & 0xFF);
		src[1] =  (byte) ((value>>8) & 0xFF);
		src[0] =  (byte) (value & 0xFF);
		return src;
	}
	/**
	 * 将int数值转换为占四个字节的byte数组，本方法适用于(高位在前，低位在后)的顺序。  和bytesToInt2（）配套使用
	 */
	public static byte[] intToBytesBig2(int value)
	{
		byte[] src = new byte[4];
		src[0] = (byte) ((value>>24) & 0xFF);
		src[1] = (byte) ((value>>16)& 0xFF);
		src[2] = (byte) ((value>>8)&0xFF);
		src[3] = (byte) (value & 0xFF);
		return src;
	}


}
